package IO;

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class IODemo9 {
    public static void main(String[] args) {
        //
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查询的根目录");
        File root = new File(scanner.nextLine());
        if(!root.isDirectory()){
            System.out.println("您输入的不是目录,请重新输入");
            return;
        }
        System.out.println("请输入要查询的词");
        String word = scanner.next();

        //递归查询
        func(word,root);
    }

    private static void func(String word, File root) {
        //列出当前路径的内容,如果没有就递归结束
        File []array = root.listFiles();
        if(array == null){
            //如果是空就没必要递归了
            return ;
        }
        for (File file : array) {
            //如果是普通文件就搜索
            if (file.isFile()) {
                String content = readFile(file);
                System.out.println("正在查找"+file.getAbsoluteFile());
                if(content.contains(word)){
                    //如果包含
                    //打印路径
                    System.out.println(file.getAbsolutePath()+" 包含要查找的内容");
                    System.out.print("\n");
                }
            } else if (file.isDirectory()) {
                //如果是目录就往下递归
                func(word, file);
            }
        }


    }

    private static String readFile(File file) {
        //使用字符流来读取
        StringBuilder str = new StringBuilder();
        try (Reader reader = new FileReader(file)){
            int len = 0;
            while (true){
                len = reader.read();
                if(len == -1){
                    break;
                }
                str.append((char)(len));
            }

        }catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }

}
